//
//  FileManager+Extension.swift
//  ClockWidget
//
//  Created by TSYH on 2023/7/13.
//

import Foundation

public extension FileManager {
    func filePath(with fileName: String) -> URL? {
        guard let documentUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        return documentUrl.appendingPathComponent(fileName)
    }
    
    func fileData(with fileName: String) -> Data? {
        guard let filePath = filePath(with: fileName) else {
            return nil
        }
        if fileExists(atPath: filePath.absoluteString.localFilePath) {
            return try? Data(contentsOf: filePath)
        }
        return nil
    }
    
    func fileExists(with fileName: String) -> Bool {
        guard let filePath = filePath(with: fileName) else {
            return false
        }
        return fileExists(atPath: filePath.absoluteString.localFilePath)
    }
    
    func write(data: Data, to fileName: String) {
        guard let filePath = filePath(with: fileName) else {
            return
        }
        try? data.write(to: filePath)
    }
    
    func remove(fileName: String) {
        guard let filePath = filePath(with: fileName) else {
            return
        }
        try? removeItem(at: filePath)
    }
    
    var documentURL: URL? {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    }
    
    /// 根据目标文件名，创建文件路径
    /// - Parameters:
    ///   - fileName: 文件名
    ///   - newDirectory: 新建文件夹名称，不存在则自动创建
    ///   - directory: 沙盒文件夹类型
    /// - Returns: 返回需要的文件路径
    func createFileURL(with fileName: String,
                        newDirectory: String? = nil,
                        for directory: FileManager.SearchPathDirectory) -> URL? {
        guard var documentUrl = urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        if let newDirectory = newDirectory, !newDirectory.isEmpty {
            documentUrl = documentUrl.appendingPathComponent(newDirectory)
        }
        
        var isDirectory: ObjCBool = false
        if fileExists(atPath: documentUrl.path, isDirectory: &isDirectory) && isDirectory.boolValue == true {
            // 文件夹已存在
        } else {
            // 文件夹不存在则创建
            try? FileManager.default.createDirectory(atPath: documentUrl.path, withIntermediateDirectories: true)
        }
        return documentUrl.appendingPathComponent(fileName)
    }
    
    func createFolder(at path: String) {
        if !isFolderExists(atPath: path) {
            try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true)
        }
    }
    
    func isFolderExists(atPath path: String) -> Bool {
        let fileManager = FileManager.default
        
        var isDirectory: ObjCBool = false
        if fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && isDirectory.boolValue == true {
            return true // 文件夹已存在
        } else {
            return false // 文件夹不存在或者路径错误
        }
    }
    
    /// 获取文件信息
    func getFileAttributes(with fileURL: URL, keys: [FileAttributeKey]) -> [FileAttributeKey: Any]? {
        do {
            let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
            
            return attributes.filter({ keys.contains( $0.key) })
            
//            if let size = attributes[.size] as? NSNumber {
//                return size.intValue
//            } else {
//                Log("无法获取文件大小")
//                return nil
//            }
        } catch {
            Log("发生错误：\(error)")
            return nil
        }
    }
}
